//
// Created by yanhai on 2020/3/30.
//

#include <iostream>
#include <cstring>
#include "string.h"

String::String(const char *cstr)
{
    if (cstr) {
        m_data = new char[strlen(cstr) + 1];
        strcpy(m_data, cstr);
    } else {
        m_data = new char[1];
        *m_data = 0;
    }
}

String::String(const String &str)
{
    m_data = new char[strlen(str.m_data) + 1];
    strcpy(m_data, str.m_data);
}

String::~String()
{
    delete[] m_data;
}

String &String::operator=(const String &str)
{
    /**
     * 如果自己赋值到自己，则必须要加这个判断
     * String s1("hello");
     * s1 = s1;
     */
    if (this == &str)
        return *this;

    delete[] m_data;
    m_data = new char[strlen(str.m_data) + 1];
    strcpy(m_data, str.m_data);
    return *this;
}

std::ostream &operator<<(std::ostream &os, const String &str)
{
    return os << str.c_str();
}
